package com.zhoug.zmui;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.zhoug.common.utils.LogUtils;
import com.zhoug.zmui.utils.ZMUIBitmapUtils;

import androidx.annotation.Nullable;

/**
 * 手写签名View
 * zmui_style_ZMUILinePathView
 *
 * @Author 35574
 * @Date 2020/7/29
 * @Description
 */
public class ZMUILinePathView extends View {
    private static final String TAG = ">>>ZMUILinePathView";
    private static final boolean DEBUG = false;
    /**
     * 字体宽度
     */
    private int mFontWidth;

    /**
     * 字体颜色
     */
    private int mFontColor;


    /**
     * 背景色（指最终签名结果文件的背景颜色，默认为透明色）
     */
    private int mBackColor;

    /**
     * 笔画X坐标起点
     */
    private float mStartX;
    /**
     * 笔画Y坐标起点
     */
    private float mStartY;

    /**
     * 是否已经签名
     */
    private boolean signed;
    /***
     * 签名路径
     */
    private Path mPath = new Path();
    /**
     * 画笔
     */
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    /**
     * 画板
     */
    private Canvas mCanvas;

    /**
     * 签名图片
     */
    private Bitmap mBitmap;
    private Bitmap.Config mBitmapConfig = Bitmap.Config.ARGB_4444;

    public ZMUILinePathView(Context context) {
        this(context, null);
    }

    public ZMUILinePathView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, R.attr.zmui_style_ZMUILinePathView);
    }

    public ZMUILinePathView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ZMUILinePathView, R.attr.zmui_style_ZMUILinePathView, R.style.zmui_style_ZMUILinePathView);
        mFontWidth = a.getDimensionPixelOffset(R.styleable.ZMUILinePathView_zmui_fontWidth, 8);
        mFontColor = a.getColor(R.styleable.ZMUILinePathView_zmui_fontColor, Color.BLACK);
        mBackColor = a.getColor(R.styleable.ZMUILinePathView_zmui_backColor, Color.TRANSPARENT);
        a.recycle();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (DEBUG) {
                    LogUtils.d(TAG, "onTouchEvent:down");
                }
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                //重置路径
                mStartX = event.getX();
                mStartY = event.getY();
                mPath.reset();
                mPath.moveTo(mStartX, mStartY);
                break;
            case MotionEvent.ACTION_MOVE:
                if (DEBUG) {
                    LogUtils.d(TAG, "onTouchEvent:move");
                }
                float x = event.getX();
                float y = event.getY();
                float disX = Math.abs(x - mStartX);
                float disY = Math.abs(y - mStartY);
                //移动的距离大于5开始画轨迹
                if (disX >= 5 || disY >= 5) {
                    signed = true;
                    //画平滑的曲线,设置贝塞尔曲线的操作点是2点的终点
                    mPath.quadTo(mStartX, mStartY, (mStartX + x) / 2, (mStartY + y) / 2);
                    mStartX = x;
                    mStartY = y;
                    invalidate();
                }

                break;
            case MotionEvent.ACTION_UP:
                if (DEBUG) {
                    LogUtils.d(TAG, "onTouchEvent:up");
                }
                //更新路径到Bitmap
                mCanvas.drawPath(mPath, mPaint);
                break;
            case MotionEvent.ACTION_CANCEL:
                if (DEBUG) {
                    LogUtils.d(TAG, "onTouchEvent:cancel");
                }
                break;
        }

        return true;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //画上次的图片
        canvas.drawBitmap(mBitmap, 0, 0, mPaint);
        //画这次的路劲
        canvas.drawPath(mPath, mPaint);
    }

    public void clear() {
        signed = false;
        if (mCanvas != null) {
            //清除Bitmap
            mCanvas.drawColor(mBackColor, PorterDuff.Mode.CLEAR);
            //重画背景
            mCanvas.drawColor(mBackColor);
            //清除路劲
            mPath.reset();
            postInvalidate();
        }

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mBitmap = Bitmap.createBitmap(w, h, mBitmapConfig);
        mCanvas = new Canvas(mBitmap);
        mCanvas.drawColor(mBackColor);
        mPaint.setStrokeWidth(mFontWidth);
        mPaint.setColor(mFontColor);
        signed = false;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY) {
            width = 400;
        }
        if (MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY) {
            height = 300;
        }
        setMeasuredDimension(width, height);
    }

    /**
     * 是否签名
     *
     * @return
     */
    public boolean isSigned() {
        return signed;
    }

    /**
     * 获取签名
     *
     * @return
     */
    public Bitmap getBitmap() {
        if (isSigned() && mBitmap != null) {
            return Bitmap.createBitmap(mBitmap);
        }
        return null;
    }

    /**
     * 获取清楚四周空隙(背景)后的图片
     * @param blank 保留的边界
     * @return
     */
    public Bitmap getClipBlankBitmap(int blank) {
        if (isSigned() && mBitmap != null) {
            return ZMUIBitmapUtils.clipBlank(mBitmap,mBackColor,blank);
        }
        return null;
    }




    /**
     * 设置字体宽度
     *
     * @param fontWidth
     */
    public void setFontWidth(int fontWidth) {
        this.mFontWidth = fontWidth;
    }

    /**
     * 设置字体颜色
     *
     * @param fontColor
     */
    public void setFontColor(int fontColor) {
        this.mFontColor = fontColor;
    }

    /**
     * 设置签名背景色
     *
     * @param backColor
     */
    public void setBackColor(int backColor) {
        this.mBackColor = backColor;
    }

    /**
     * 设置签名Bitmap 的Bitmap.Config
     *
     * @param bitmapConfig
     */
    public void setBitmapConfig(Bitmap.Config bitmapConfig) {
        if(bitmapConfig!=null){
            this.mBitmapConfig = bitmapConfig;
        }
    }
}
